package com.tyut.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tyut.mapper.ArticleMapper;
import com.tyut.pojo.Article;
import com.tyut.pojo.PageBean;
import com.tyut.service.ArticleService;
import com.tyut.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
	@Autowired
 	private ArticleMapper articleMapper;
	@Override
	public void add(Article article) {
		Map<String,Object> map = ThreadLocalUtil.get();
		article.setCreateUser((Integer)map.get("id"));
		article.setUpdateTime(LocalDateTime.now());
		article.setCreateTime(LocalDateTime.now());
		articleMapper.insert(article);
	}

	@Override
	public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state,String checkState) {
		//2.开启分页查询，需要使用PageHelper插件，需要导入这个插件的坐标
		//PageHHelper会自动将pageNum和pageSize拼接到SQL语句后面，加上limit，完成一个分页查询
		PageHelper.startPage(pageNum,pageSize);
		//3.调用napper
		Map<String,Object> claim =ThreadLocalUtil.get();
		Integer userId = (Integer) claim.get("id");
		Page<Article> page  = articleMapper.list(userId,categoryId,state,checkState);
		return new PageBean(page.getTotal(),page.getResult());
	}

	@Override
	public Article detail(Integer id) {
		return articleMapper.detail(id);
	}

	@Override
	public void update(Article article) {
		Map<String,Object> claim =ThreadLocalUtil.get();
		String username = (String) claim.get("username");
		article.setCheckName(username);
		article.setUpdateTime(LocalDateTime.now());
		articleMapper.update(article);
	}

	@Override
	public void delete(Integer id) {
		articleMapper.delete(id);
	}

	@Override
	public void check(Article article) {
		Map<String,Object> map = ThreadLocalUtil.get();
		article.setCheckName((String) map.get("username"));
		articleMapper.update(article);;
	}
}
